package com.kasax.plugin.shadow.visitor

import com.kasax.plugin.shadow.ShadowExtenstion
import com.kasax.plugin.shadow.utils.LogUtils
import org.objectweb.asm.ClassVisitor
import org.objectweb.asm.commons.ClassRemapper
import org.objectweb.asm.commons.Remapper

class PackageRemappingClassVisitor extends ClassRemapper {
    private static final String TAG = "PackageRemappingClassVisitor"

    PackageRemappingClassVisitor(ClassVisitor classVisitor, ShadowExtenstion shadowExtenstion) {
        super(classVisitor, new Remapper() {
            @Override
            String map(String internalName) {
//                if (internalName.startsWith(OLD_PACKAGE)) {
//                    def newName = NEW_PACKAGE + internalName.substring(OLD_PACKAGE.length())
//                    LogUtils.d(TAG, "Remapping package: $internalName -> $newName")
//                    return newName
//                }
//                if (internalName.equals(GSON_OLD_CLASS)) {
//                    LogUtils.d(TAG, "Remapping class: $internalName -> $GSON_NEW_CLASS")
//                    return GSON_NEW_CLASS
//                }
//                return internalName

                if (shadowExtenstion == null || shadowExtenstion.relocPkgs == null || shadowExtenstion.relocPkgs.
                        isEmpty()) {
                    LogUtils.d(TAG, "unused pkg reloc func")
                    return internalName
                }

                // 判断是否是支持的
                def result = shadowExtenstion.relocPkgs.find {
                    String tmpInternalName = internalName.replaceAll("/", ".")
//                    LogUtils.d(TAG, "map s-internalName: $internalName , new-internalName: $tmpInternalName,  t-key: " +
//                            "${it.key}")
                    tmpInternalName.startsWith(it.key)
                }

//                LogUtils.d(TAG, "result: ${result}")
                if (result != null) {
//                    LogUtils.d(TAG, "map find result: ${result.key} , value: ${result.value}")
                    String tmpNewPkg = result.value.replace('.','/')
                    String temOldPkg = result.key.replace('.','/')

                    LogUtils.d(TAG, "map find temOldPkg: ${temOldPkg} , tmpNewPkg: ${tmpNewPkg}")

                    def newName = tmpNewPkg + internalName.substring(temOldPkg.length())
                    LogUtils.d(TAG, "Remapping package: $internalName -> $newName")
                    return newName
                }
                return internalName
            }
        })
    }
}
